package br.com.android.pubclub.web;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import br.com.android.pubclub.R;
import br.com.android.pubclub.basicas.Cliente;
import br.com.android.pubclub.basicas.Saldo;
import br.com.android.pubclub.dados.ThreadAmizadesAcoes;
import br.com.android.pubclub.dados.ThreadPresentearMeuSaldo;

public class MeuSaldo extends ListActivity {

	ProgressDialog pd;
	Handler handler;
	EditText edtNomeBusca;
	ArrayList<Saldo> meuSaldo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tela_de_busca_generica);
		setTitle(R.string.title_MeuSaldo);

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				atualizarInterface(msg);
			}

		};

		new ThreadPresentearMeuSaldo(handler,
				ThreadPresentearMeuSaldo.MEU_SALDO, null).start();
		
		edtNomeBusca = (EditText) findViewById(R.id.edtBusca);
		edtNomeBusca.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				ArrayList<Saldo> meuSaldoBusca = new ArrayList<Saldo>();

				String nomeBusca = edtNomeBusca.getText().toString()
						.toLowerCase().trim();

				for (Saldo saldo : meuSaldo) {

					if (saldo.getBedida().getDescricao().trim().toLowerCase().contains(nomeBusca)) {

						meuSaldoBusca.add(saldo);
					}

				}
				
				setListAdapter(new MeuSaldoAdapter(meuSaldoBusca));

			}
		});


	}

	public void refresh(View v) {

		new ThreadPresentearMeuSaldo(handler,
				ThreadPresentearMeuSaldo.MEU_SALDO, null).start();

	}

	protected void atualizarInterface(Message msg) {
		// TODO Auto-generated method stub

		switch (msg.what) {

		case ThreadAmizadesAcoes.EXECUTANDO:

			pd = new ProgressDialog(this);

			pd.setMessage("Atualizando...");
			pd.show();

			break;

		case ThreadAmizadesAcoes.EXIBINDO:

			meuSaldo = (ArrayList<Saldo>) msg.getData()
					.getSerializable("meuSaldo");
			setListAdapter(new MeuSaldoAdapter(meuSaldo));

			break;

		case ThreadAmizadesAcoes.CONCLUIDO:

			pd.dismiss();
			break;

		}

	}

}
